package moni.anyou.com.view.view.my.invitefamily;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import org.json.JSONException;
import org.json.JSONObject;
import org.kymjs.aframe.http.KJHttp;
import org.kymjs.aframe.http.KJStringParams;
import org.kymjs.aframe.http.StringCallBack;
import moni.anyou.com.view.config.AnyouerApplication;
import moni.anyou.com.view.tool.PermissionTools;
import moni.anyou.com.view.widget.dialog.PopAddSuccess;
import moni.anyou.com.view.R;
import moni.anyou.com.view.base.BaseActivity;
import moni.anyou.com.view.config.SysConfig;
import moni.anyou.com.view.tool.AppTools;
import moni.anyou.com.view.tool.ToastTools;
import moni.anyou.com.view.tool.VerificationTools;
import moni.anyou.com.view.widget.NetProgressWindowDialog;
import moni.anyou.com.view.widget.dialog.MessgeDialog;
import moni.anyou.com.view.wxapi.wxutil.Util;

public class InviteFriendActivity extends BaseActivity implements View.OnClickListener {
    private NetProgressWindowDialog window;
    private EditText  etPhoneNum;
    private EditText etNick;
    private EditText etRole;
    private RadioGroup radiogroup_relation;
    private String teamid = "0";
    private Button btn_commit;
    private PopAddSuccess mPopAddFamilySuccess;
    MessgeDialog mPDialog;
    //权限
    private int RequestCode = 0x1983;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invite_friend);
        init();
        teamid =  getIntent().getStringExtra("teamID");
    }
    @Override
    public void setAction() {
        super.setAction();
    }
    @Override
    public void setData() {
        super.setData();
    }
    @Override
    public void initView() {
        super.initView();
        initTitle();
        window = new NetProgressWindowDialog(mBaseActivity);
        btn_commit = (Button) findViewById(R.id.btn_commit);
        etNick = (EditText) findViewById(R.id.et_nick);
        etPhoneNum = (EditText) findViewById(R.id.et_mobile);
        tvTitle.setText("邀请朋友");
        ivBack.setOnClickListener(this);
        btn_commit.setOnClickListener(this);
        mPDialog = new MessgeDialog((InviteFriendActivity) mBaseActivity);
        mPDialog.setMRL("获取读写权限", "取消", "立即获取");
        mPDialog.setListener();
        mPDialog.setMsgDialogListener(new MessgeDialog.MsgDialogListener() {
            @Override
            public void OnMsgClick() {

            }

            @Override
            public void OnLeftClick() {
                onBack();
            }

            @Override
            public void OnRightClick() {
                openPermissionSettingPage(RequestCode);
            }

            @Override
            public void onDismiss() {
                onBack();
            }
        });
    }
    int wxSdkVersion = 0;
    private static final int TIMELINE_SUPPORTED_VERSION = 0x21020001;
    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }
    public void shareWechat(ShareMsgResBean bean) {
        try {
            bean.title = "发送组团邀请";
            PopAddSuccess.SentInfoBean bean2 = mPopAddFamilySuccess.getsentInf();
            bean.content = "你的朋友：" + SysConfig.userInfoJson.getString("nick") + "邀请您参加徒步活动，请登录系统后到我的消息里点击接受邀请即可";
            WXWebpageObject webpage = new WXWebpageObject();
            webpage.webpageUrl = "";
            WXMediaMessage msg = new WXMediaMessage(webpage);
            msg.title = bean.title;
            msg.description = bean.content;
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
            Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 90, 90, true);
            bmp.recycle();
            msg.thumbData = Util.bmpToByteArray(thumbBmp, true);
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = buildTransaction("webpage");
            req.message = msg;
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
            AnyouerApplication.mIWXAPI.sendReq(req);
        }
        catch(Exception ex){

        }
    }



    class ShareMsgResBean {
        //分享url
        public String url;
        //分享标题
        public String title;
        //分享内容
        public String content;
        //分享图片
        public String image;
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_left:
                onBack();
                activityAnimation(RIGHT_OUT);
                break;
            case R.id.btn_commit:
                if (TextUtils.isEmpty(etNick.getText())) {
                    ToastTools.showShort(mContext, "昵称不能为空");
                    return;
                }
                if (TextUtils.isEmpty(etPhoneNum.getText())) {
                    ToastTools.showShort(mContext, "邀请号码不能为空");
                    return;
                }
                if (!VerificationTools.isMobile(etPhoneNum.getText().toString()) && etPhoneNum.getText().toString().length() != 11) {
                    ToastTools.showShort(mContext, "请输入正确的手机号码");
                    return;
                }

                getAddFriend();
                break;
            case R.id.llMsg:
                mPopAddFamilySuccess.dismiss();
                requestPermission(PermissionTools.sendSms);
                break;
            case R.id.llWechat:
                if (wxSdkVersion >= TIMELINE_SUPPORTED_VERSION) {
                    shareWechat(new ShareMsgResBean());
                } else {
                    ToastTools.showShort(mContext, "您还未安装微信，该功能暂不能使用");
                }

                break;
            default:
                break;
        }
    }

    public void getAddFriend() {

        KJHttp kjh = new KJHttp();
        KJStringParams params = new KJStringParams();
        String cmdPara = "{\"cmd\":\"2\",\"uid\":\"" + SysConfig.uid +"\",\"token\":\""+ SysConfig.token+"\",\"mobile\":\""+ etPhoneNum.getText().toString() +"\",\"nick\":\""+etNick.getText().toString()+"\",\"teamid\":\""+ teamid+"\"}";
        params.put("sendMsg", cmdPara);
        window.ShowWindow();
        kjh.urlGet(SysConfig.ServerUrl, params, new StringCallBack() {
            @Override
            public void onSuccess(String t) {

                //Log.d(TAG, "onSuccess: " + t);
                try {
                    JSONObject jsonObject = new JSONObject(t);
                     //Toast.makeText(InviteFriendActivity.this, t, Toast.LENGTH_LONG).show();
                    int result = Integer.parseInt(jsonObject.getString("result"));
                    if (result >= 1) {
                        //Toast.makeText(mContext, "邀请成功，密码为手机后6位", Toast.LENGTH_LONG).show();
                        //onBack();
                        mPopAddFamilySuccess = new PopAddSuccess(InviteFriendActivity.this,etPhoneNum.getText().toString(),jsonObject.getString("retmsg"),InviteFriendActivity.this);
                        mPopAddFamilySuccess.showAtLocation(mBaseActivity.findViewById(R.id.pop_need), Gravity.CENTER, 0, 0);
                        mPopAddFamilySuccess.isShowing();

                    } else {
                        if (result == -2) {
                            AppTools.jumptoLogin(mBaseActivity);
                        }
                        Toast.makeText(mContext, jsonObject.getString("retmsg"), Toast.LENGTH_LONG).show();

                    }
                } catch (Exception ex) {
                    Toast.makeText(mContext, ex.toString(), Toast.LENGTH_LONG).show();

                }
                window.closeWindow();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                //Toast.makeText(mContext, "网络异常，请稍后再试", Toast.LENGTH_LONG).show();
                window.closeWindow();
            }
        });
    }

    @Override
    public void permissionAlreadyRefuse(String permissionName) {
        super.permissionAlreadyRefuse(permissionName);
        mPDialog.show();
    }

    @Override
    public void permissionRefuse(String permissionName) {
        super.permissionRefuse(permissionName);
        mPDialog.show();
    }

    @Override
    public void permissionSuccess(String permissionName) {
        try {
            super.permissionSuccess(permissionName);
            PopAddSuccess.SentInfoBean bean = mPopAddFamilySuccess.getsentInf();
            String message = "你的朋友：" + SysConfig.userInfoJson.getString("nick") + "邀请您参加徒步活动，请登录系统后到我的消息里点击接受邀请即可";
            AppTools.sendMsg(mBaseActivity, bean.getPhoneNum(), message);
        }
        catch(Exception ex){

        }
    }

    @Override
    public void permissionNoNeed(String permissionName) {
        try {
            super.permissionNoNeed(permissionName);
            PopAddSuccess.SentInfoBean bean = mPopAddFamilySuccess.getsentInf();
            String message = "你的朋友：" + SysConfig.userInfoJson.getString("nick") + "邀请您参加徒步活动，请登录系统后到我的消息里点击接受邀请即可";
            AppTools.sendMsg(mBaseActivity, bean.getPhoneNum(), message);
        } catch (Exception ex) {

        }
    }
}
